package com.cheetah.start.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.alibaba.fastjson.JSONObject;
import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.common.base.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.handle.ModelAndView;

/**
 * 全局异常拦截
 *
 * @author 25175
 * @date 2022/6/18 17:34
 */
@Slf4j
@Component
public class GlobalExceptionFilter implements Filter {

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
            int status = ctx.status();
            if (!ctx.getHandled() || status == 404) {
                ctx.status(200);
                ctx.setHandled(true);
                ctx.render(new ModelAndView("/error/404.html"));
            }
            if (!ctx.getHandled() || status == 500) {
                ctx.status(200);
                ctx.setHandled(true);
                ctx.render(new ModelAndView("/error/500.html"));
            }
            if (!ctx.getHandled() || status == 403) {
                ctx.status(200);
                ctx.setHandled(true);
                ctx.render(new ModelAndView("/error/403.html"));
            }
        } catch (Throwable e) {
            ctx.status(200);
            //ctx.setHandled(true);
            //String url = ctx.url();
            //log.info(url);
            //Object controller = ctx.controller();
            //log.info("控制器:[{}]",controller);

            if (e instanceof NotLoginException) {
                Result<Object> failure = Result.failure(ResultCode.NOT_LOGIN.getCode(), "未登录");
                ctx.result = failure;
                // ctx.redirect("/login");
                ctx.outputAsJson(JSONObject.toJSONString(failure));
            } else if (e instanceof CheetahException) {
                Result<Object> failure = Result.failure(e.getMessage());
                ctx.result = failure;
                ctx.outputAsJson(JSONObject.toJSONString(failure));
            } else if (e instanceof Exception) {
                log.error("全局 Exception 异常", e);
                Result<Object> failure = Result.failure(e.getMessage());
                ctx.result = failure;
                ctx.outputAsJson(JSONObject.toJSONString(failure));
            } else {
                log.error("全局 Throwable 异常", e);
                Result<Object> failure = Result.failure(e.getMessage());
                ctx.result = failure;
                ctx.outputAsJson(JSONObject.toJSONString(failure));
            }
        }
    }
}
